package com.hotchpotch.tool.popwindow;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.ProgressBar;

import com.hotchpotch.R;
import com.hotchpotch.util.MyUtil;


/**
 * Created by Administrator on 2017/5/19 0019.
 */

public class RefreshPopwindow extends PopupWindow {
    private Context mContext;
    //屏幕的宽度和高度
    private int mScreenWidth, mScreenHeight;
    //位置不在中心
    private int popupGravity = Gravity.CENTER;
    private ProgressBar progressBar;
    private boolean isShow = false;

    public RefreshPopwindow(Context context) {
        this.mContext = context;

        //设置可以获得焦点
        setFocusable(false);
        //设置弹窗内可点击
        setTouchable(false);
        //设置弹窗外可点击
        setOutsideTouchable(false);
        //设置动画效果
        setAnimationStyle(R.style.anim_scale_alpha);

        //获得屏幕的宽度和高度
        mScreenWidth = MyUtil.getScreenWidth(mContext);
        mScreenHeight = MyUtil.getScreenHeight(mContext);
        //设置弹窗的宽度和高度
        setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        setBackgroundDrawable(new BitmapDrawable());
        //设置弹窗的布局界面
        setContentView(LayoutInflater.from(mContext).inflate(R.layout.pop_refresh, null));
        initUI();
    }

    /**
     * 初始化弹窗列表
     */
    private void initUI() {
        progressBar = (ProgressBar) getContentView().findViewById(R.id.pop_progress);
        setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss() {
                isShow = false;
                backgroundAlpha((Activity) mContext, 1f);
            }
        });
    }

    /**
     * 显示弹窗列表界面
     */
    public void showView(View view) {
        isShow = true;
        //显示弹窗的位置
        showAtLocation(view, popupGravity, 0, 0);
        backgroundAlpha((Activity) mContext, 1.0f);
    }

    public void dismissView() {
        if (isShow) {
            dismiss();
        }
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(Activity context, float bgAlpha) {
        WindowManager.LayoutParams lp = context.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        context.getWindow().setAttributes(lp);
    }
}
